import { registerMapItem, type MapItemGroup, type MapItem, addMapItemInfoView } from '@/map-item'
import { entityMapItem, entityMapItemType } from '../base'
import type { Airport } from '../airport'
import type { Waypoint } from '../waypoint'
import type { Routing } from './types'
import { highLightRoutingFeatures } from './feature'
import { routingByAirport, routingIndex } from './routing-index'
import { routingLayer } from './map'
import { RoutingInfoVue, WaypointRoutingList } from './info'

function search(
  lng: number,
  lat: number,
  radius: number,
  result: Record<string, MapItemGroup<any>>
): Set<Routing> | null {
  let set: Set<Routing> | null = routingIndex.search(lng, lat, radius)
  const apts = result[entityMapItemType('Airport')] as MapItemGroup<Airport>
  if (apts && apts.items) {
    if (!set) {
      set = new Set()
    }
    for (const apt of apts.items) {
      const rLst = routingByAirport.get(apt.id)
      if (rLst) {
        for (const rr of rLst) {
          set.add(rr)
        }
      }
    }
  }

  if (!set) {
    return null
  }
  return set
}

export function initRoutingMapItems() {
  registerMapItem<Routing>({
    type: entityMapItemType('Routing'),
    typeName: '飞行路线',
    icon: 'mas-icon-Routing',
    getName: (t) => t.id,
    highlight: highLightRoutingFeatures,
    index: {
      enable: () => routingLayer.visible,
      search
    },
    infoView: RoutingInfoVue
  })
  addMapItemInfoView<Waypoint>(entityMapItemType('Waypoint'), WaypointRoutingList)
}

export function routingMapItem(id: string): MapItem<Routing> {
  return entityMapItem('Routing', id)
}
